/*

  The MIT License

  Copyright (c) 2008 - 2011. Dimarik

  Permission is hereby granted, free of charge, to any person obtaining a copy
  of this software and associated documentation files (the "Software"), to deal
  in the Software without restriction, including without limitation the rights
  to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  copies of the Software, and to permit persons to whom the Software is
  furnished to do so, subject to the following conditions:

  The above copyright notice and this permission notice shall be included in
  all copies or substantial portions of the Software.

  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  THE SOFTWARE.

*/

package ru.goodcore.swf
{

import flash.geom.Rectangle;
import flash.utils.ByteArray;
import flash.utils.Endian;
import flash.utils.IDataInput;

import ru.goodcore.core.ProductInfo;

/**
 *  @author				Dimarik
 *  @version			1.1
 *  @langversion		3.0
 *  @playerversion		9.0
 * 
 */
public class SWFInfo extends ByteArray {

	//-------------------------------------------------------------------------
	//
	//   Constructor
	//
	//-------------------------------------------------------------------------

	public function SWFInfo(data:ByteArray):void {
		super();
		super.endian = Endian.LITTLE_ENDIAN;

		var endian:		String = data.endian;
		var position:	uint = data.position;
		var signature:	String;
		
		data.endian = Endian.LITTLE_ENDIAN;
		data.position = 0;

		if (data.bytesAvailable > 26) {
			signature = data.readUTFBytes(3);

			if (signature == 'FWS' || signature == 'CWS') {
				this._version = data.readUnsignedByte();
				this._uncompressedSize = data.readUnsignedInt();
				data.readBytes(this);
				if (signature == 'CWS') {
					this._isCompressed = true;
					super.uncompress();
				}
			} else throw new ArgumentError('Data file is not valid swf file.');

			this.readHeader();

			var tag:	SWFTag;
			while (super.bytesAvailable) {
				tag = new SWFTag(this);

				//trace(tag.toString())

				switch (tag.tagId) {
					case 41: // ProductInfo
						this._productInfo = new ProductInfo();
						this._productInfo.readExternal(tag.body);
						break;

					case 58: // EnableDebugger
					case 63: // DebugID
					case 64: // EnableDebugger2
						this._hasDebugInfo = true;
						break;

					case 69: // FileAttributes
						var byte:uint = tag.body.readUnsignedByte();
						this._useDirectBlit = (byte & (1 << 1)) > 0;
						this._useGPU = (byte & (1 << 2)) > 0;
						this._hasMetaData = (byte & (1 << 3)) > 0;
						this._actionScript3 = (byte & (1 << 4)) > 0;
						this._useNetwork = (byte & (1 << 7)) > 0;
						break;

					case 77: // Metadata
						this._metaData = new XML( tag.body.readUTFBytes(tag.body.length) );
						break;
				}
			}
		}

		data.endian = endian;
		data.position = position;
	}

	//-------------------------------------------------------------------------
	//
	//   Properties
	//
	//-------------------------------------------------------------------------

	/**
	 * @private
	 */
	private var _version:uint;

	public function get version():uint {
		return this._version;
	}

	/**
	 * @private
	 */
	private var _metaData:	XML;

	public function get metaData():XML {
		return this._metaData;
	}

	/**
	 * @private
	 */
	private var _isCompressed:	Boolean = false;

	public function get isCompressed():Boolean {
		return this._isCompressed;
	}

	/**
	 * @private
	 */
	private var _hasDebugInfo:	Boolean = false;

	public function get hasDebugInfo():Boolean {
		return this._hasDebugInfo;
	}

	/**
	 * @private
	 */
	private var _uncompressedSize:	uint;

	public function get uncompressedSize():uint {
		return this._uncompressedSize;
	}

	/**
	 * @private
	 */
	private var _frameRate:	Number;

	public function get frameRate():Number {
		return this._frameRate;	
	}

	/**
	 * @private
	 */
	private var _rect:	Rectangle;

	public function get rect():Rectangle {
		return this._rect;
	}

	/**
	 * @private
	 */
	private var _numFrames:	uint;

	public function get numFrames():uint {
		return this._numFrames;
	}

	/**
	 * @private
	 */
	private var _useDirectBlit:	Boolean = false;

	public function get useDirectBlit():Boolean {
		return this._useDirectBlit;
	}

	/**
	 * @private
	 */
	private var _useGPU:	Boolean = false;

	public function get useGPU():Boolean {
		return this._useGPU;
	}

	/**
	 * @private
	 */
	private var _hasMetaData:	Boolean = false;

	public function get hasMetaData():Boolean {
		return this._hasMetaData;
	}

	/**
	 * @private
	 */
	private var _actionScript3:	Boolean = false;

	public function get actionScript3():Boolean {
		return this._actionScript3;
	}

	/**
	 * @private
	 */
	private var _useNetwork:	Boolean = false;

	public function get useNetwork():Boolean {
		return this._useNetwork;
	}

	/**
	 * @private
	 */
	private var _productInfo:	ProductInfo;

	public function get productInfo():ProductInfo {
		return this._productInfo;
	}


	//-------------------------------------------------------------------------
	//
	//   Private variables
	//
	//-------------------------------------------------------------------------

	/**
	 * @private
	 */
	private var _bitIndex:	uint;

	//-------------------------------------------------------------------------
	//
	//   Public methods
	//
	//-------------------------------------------------------------------------

	public function readRect():Rectangle {
		var pos:uint = super.position;
		var byte:uint = this[pos];
		var bits:uint = byte >> 3;
		var xMin:Number = this.readBits(bits, 5) / 20;
		var xMax:Number = this.readBits(bits) / 20;
		var yMin:Number = this.readBits(bits) / 20;
		var yMax:Number = this.readBits(bits) / 20;
		super.position = pos + Math.ceil(((bits * 4) - 3) / 8) + 1;
		return new Rectangle(xMin, yMin, xMax - xMin, yMax - yMin);
	}

	public function readBits(length:uint, start:int = -1):Number {
		if (start < 0) start = this._bitIndex;
		this._bitIndex = start;
		var byte:uint = this[super.position];
		var out:Number = 0;
		var shift:Number = 0;
		var currentByteBitsLeft:uint = 8 - start;
		var bitsLeft:Number = length - currentByteBitsLeft;

		if (bitsLeft > 0) {
			super.position++;
			out = this.readBits(bitsLeft, 0) | ((byte & ((1 << currentByteBitsLeft) - 1)) << bitsLeft);
		} else {
			out = (byte >> (8 - length - start)) & ((1 << length) - 1);
			this._bitIndex = (start + length) % 8;
			if (start + length > 7) super.position++;
		}

		return out;
	}

	public function readUnsignedInt64(input:IDataInput):Number {
		input = input || this;
		var n1:Number = input.readUnsignedInt();
		var n2:Number = input.readUnsignedInt();
		return n2 * 0x100000000 + n1;	
	}

	public override function toString():String {
		var result:String = 
			'[SWFInfo: \n\tversion: ' + this._version + 
			(this._productInfo ? '\n\t' + this._productInfo.toString() : '') + 
			'\n\tframeRate: ' + this._frameRate + 
			'\n\thasDebugInfo: ' + this._hasDebugInfo + 
			'\n\tnumFrames: ' + this._numFrames + 
			'\n\tcompressed: ' + this._isCompressed + 
			'\n\tuncompressedSize: ' + this._uncompressedSize + ' bytes' +
			'\n\tdimension: ' + this._rect.width + 'x' + this._rect.height + ' px' +
			'\n\thasMetadata: ' + this._hasMetaData + 
			'\n]';
		return result;
	}

	//-------------------------------------------------------------------------
	//
	//   Private methods
	//
	//-------------------------------------------------------------------------

	/**
	 * @private
	 */
	private function readFrameRate():Number {
		return this._version < 8 ?
			super.readUnsignedShort() :
			super.readUnsignedByte() / 0xFF  + super.readUnsignedByte();
	}

	/**
	 * @private
	 */
	private function readHeader():void {
		this._rect = this.readRect();
		this._frameRate = this.readFrameRate();		
		this._numFrames = super.readShort();
	}

}
}